package com.ruoyi.mysystem.service.impl;

import com.alipay.api.AlipayApiException;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.mysystem.domain.SysOrder;
import com.ruoyi.mysystem.mapper.SysOrderMapper;
import com.ruoyi.mysystem.service.ISysAdService;
import com.ruoyi.mysystem.service.ISysOrderService;
import com.ruoyi.mysystem.util.AliPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Service
public class SysAdService implements ISysAdService {
    @Autowired
    private AliPayUtil aliPayUtil;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysOrderMapper sysOrderMapper;

    @Override
    public HashMap getAlipayView(Double money, String textContent, String frontCover, Long expireDate,String username) throws AlipayApiException {
        String alipayView = "";
        //验证提交的支付金额
        Double[] arr = {10.0, 50.0, 188.0, 588.0, 999.0, 1888.0};
        boolean contains = Arrays.asList(arr).contains(money);
        HashMap hashMap = new HashMap();
        if (contains) {
            String outTradeNo = String.valueOf(System.currentTimeMillis());

            hashMap.put("orderNum",Long.valueOf(outTradeNo));
            //创建预支付界面
            alipayView = aliPayUtil.getAlipayView(money, outTradeNo);

            //创建订单
            SysOrder sysOrder = new SysOrder();
            sysOrder.setOrderNum(Long.valueOf(outTradeNo));
            sysOrder.setTradeMerchant("寻惠");
            sysOrder.setOrderStatus("0");
            String goodsName = "";
            if (money == 10.0) {
                goodsName = "广告服务-一天";
            } else if (money == 50.0) {
                goodsName = "广告服务-一周";
            } else if (money == 188.0) {
                goodsName = "广告服务-一月";
            } else if (money == 588.0) {
                goodsName = "广告服务-三月";
            } else if (money == 999.0) {
                goodsName = "广告服务-半年";
            } else if (money == 1888.0) {
                goodsName = "广告服务-一年";
            }
            sysOrder.setTradeGoods(goodsName);
            sysOrder.setOrderMoney(money);
            sysOrder.setCreateBy(username);
            sysOrder.setCreateTime(new Date());
            sysOrderMapper.insertSysOrder(sysOrder);
            //暂存用户发布的广告信息，当用户付款成功，则发布到数据库
            redisCache.setCacheObject("adDetails_" + outTradeNo, textContent, 5, TimeUnit.MINUTES);
            redisCache.setCacheObject("adFrontCover_" + outTradeNo, frontCover, 5, TimeUnit.MINUTES);
            redisCache.setCacheObject("adExpireDate_" + outTradeNo, expireDate, 5, TimeUnit.MINUTES);
        }
        hashMap.put("res",alipayView);
        return hashMap;
    }

    @Override
    public String getAdDetailsList() {
        return null;
    }

    /**
     * 添加广告信息
     */
}
